<template>
  <div>
    <div>
      <div style="margin-top: 15px;">
        <el-input placeholder="请输入姓名" v-model="keyWord" style="width: 400px">
          <el-button slot="append" icon="el-icon-search" @click="searchByKeyword()"></el-button>
        </el-input>
        <el-button type="success" plain @click="refresh">点击刷新</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="clear()"></el-button>
        <el-button type="success" round @click="addDialogVisible = true">新增用户</el-button>
      </div>
    </div>
    <!-- 列表 -->
    <el-table :data="tableData" border style="width: 50%;margin: 0 auto;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="userId" label="账号" width="180">
      </el-table-column>
      <el-table-column prop="userName" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="password" label="密码">
      </el-table-column>
      <el-table-column prop="sex" label="性别">
      </el-table-column>
      <el-table-column prop="age" label="年龄">
      </el-table-column>
      <el-table-column prop="location" label="地址">
      </el-table-column>

      <el-table-column prop="name" label="操作" align="center">
        <template slot-scope="scope">
          <!-- (scope.row.userId)用于获取当前行数据对象中的用户ID（或其他字段） -->
          <el-button size="mini" type="text" @click="openDialog(scope.row)">编辑</el-button>

          <el-button size="mini" type="text" @click="deleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 编辑 -->
    <el-dialog title="编辑用户" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" label="top">
      <el-form label-width="80px">
        <el-form-item label="id">
          <el-input v-model="user.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="user.userId" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="user.userName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="user.sex" placeholder="请输入性别"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="user.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="user.location" placeholder="请输入地址"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增用户 -->
    <el-dialog title="新增用户" :visible.sync="addDialogVisible" width="30%" :before-close="handleClose" label="top">
      <el-form label-width="80px">

        <el-form-item label="账号">
          <el-input v-model="addUser.userId" placeholder="请输入账号" minlength="1" maxlength="8"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="addUser.userName" placeholder="请输入姓名" minlength="2" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addUser.password" placeholder="请输入密码" minlength="5" maxlength="10"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <div>
      <el-pagination @size-change="handleSizeChange" @prev-click="prevClick" @next-click="nextClick"
        @current-change="handleCurrentChange" background layout="total,sizes,prev, pager, next,jumper" :total="total"
        :page-sizes="[10, 20, 50, 100, 500, 2000]">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [], // 数据列表
      keyWord: '',
      dialogVisible: false,
      selectedRows: [],
      total: 0, // 数据总数
      pageNum: 0,
      pageSize: 10,

      user: {
        userName: '',
        location: '',
        password: '',
        userId: '',
        sex: '',
        age: '',
        id: ''
      },
      addDialogVisible: false,
      addUser: {
        userName: '',
        password: '',
        userId: '',

      }

    }
  },
  mounted() {
    this.selectUser(1, 10, "");
  },
  methods: {

    //分页
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.selectUser();
    },
    prevClick(pageNum) {
      this.pageNum = pageNum
      this.selectUser();
    },
    nextClick(pageNum) {
      this.pageNum = pageNum
      this.selectUser();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.selectUser();
    },
    selectUser() {
      this.$request.post('user/selectUser',
        {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          keyWord: this.keyWord,

        }).then((res) => {
          console.log(JSON.stringify(res));
          let result = res.data;
          this.tableData = result.list;
          this.total = result.total;
        })
    },
    //删除
    deleteUser(userId) {
      // 弹出确认对话框
      this.$confirm("确认要删除吗？").then(() => {
        // 用户点击了确认按钮

        this.$request.post('user/deleteUser/' + userId)
          .then((res) => {
            // 显示删除成功
            this.$message({
              message: res.message,
              type: "success",
            });
            // 刷新表格数据
            this.selectUser();
          });
      }).catch(() => {
        // 用户点击了取消按钮
        // 执行取消操作或不执行任何操作
      });
    },
    refresh() {
      this.selectUser(1, 10, '');
    },
    // 搜索
    searchByKeyword() {
      const keyWord = this.keyWord
      if (keyWord == '') {
        this.$message({
          message: '请输入姓名',
          type: "error",
        });
      } else {
        this.$request.post('user/selectUser',
          { keyWord: keyWord }
        ).then((res) => {
          console.log(JSON.stringify(res));
          if (res.code == '200') {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.tableData = res.data.list;
            this.total = res.data.total;
          }

        });
      }

    },
    openDialog(user) {
      this.dialogVisible = true;
      // 更新 userId 变量
      this.user.id = user.id;
      this.user.userId = user.userId;
      this.user.userName = user.userName;
      this.user.location = user.location;
      this.user.password = user.password;
      this.user.sex = user.sex;
      this.user.age = user.age;
    },
    //编辑用户
    updateUser() {
      if (!this.user.userName) {
        this.$message.error("用户名不能为空");
        return;
      }
      if (/[*&%$#@!]/.test(this.user.location)) {
        this.$message.error("地点不能包含特殊字符");
        return;
      }
      // 对 password 进行校验
      if (!/(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{6,}/.test(this.user.password)) {
        this.$message.error("密码必须包含大小写字母和数字，且长度不少于6位");
        return;
      }
      // 对 sex 进行校验
      if (this.user.sex !== "男" && this.user.sex !== "女") {
        this.$message.error("性别只能是男或女");
        return;
      }

      // 对 age 进行校验
      if (this.user.age <= 0) {
        this.$message.error("年龄不符");
        return;
      }
      const data = {
        userName: this.user.userName,
        location: this.user.location,
        password: this.user.password,
        id: this.user.id,
        sex: this.user.sex,
        age: this.user.age,
        userId: this.user.userId

      };
      this.$request.post('/user/updateUser', data)
        .then((res) => {
          this.$message({
            message: res.message,
            type: 'success'
          });
          this.dialogVisible = false,
            this.selectUser();

        });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    // 获取element中的勾选的行
    handleSelectionChange(rows) {
      this.selectedRows = rows;
      console.log('用户选择的行数据：', this.selectedRows);
    },
    // 批量删除
    clear() {
      const selectedRows = this.selectedRows.map(item => item.id);
      if (this.selectedRows.length <= 0) {
        this.$message({
          message: "请勾选数据",
          type: "error",
        });
      } else {
        this.$confirm("确认要删除吗？")
          .then((_) => {
            this.$request.post('/user/clearUser', selectedRows)
              .then((res) => {
                this.$message({
                  message: res.message,
                  type: "success",
                });
                this.selectUser();
              })
          })
          .catch((_) => { });
      }
    },
    // 新增用户
    addUsers() {

      //校验数据：非空校验、长度检验、格式校验、是否包含敏感词校验、特殊字符校验、复杂度校验
      if (this.addUser.userId === '') {
        this.$message.error("请输入账号");
        return;
      }

      const userIdRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,}$/;
      if (!userIdRegex.test(this.addUser.userId)) {
        this.$message.error("账号必须包含数字小写字母大写字母，并且长度为8位");
        return;
      }

      if (this.addUser.userName === '') {
        this.$message.error("请输入姓名");
        return;
      }

      if (this.addUser.password === '') {
        this.$message.error("请输入密码");
        return;
      }
      const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{10}$/;;
      if (!passwordRegex.test(this.addUser.password)) {
        this.$message.error("密码必须包含数字小大写字母特殊符号，并且长度为10位");
        return;
      }

      this.$request.post('user/register', this.addUser)
        .then((res) => {
          //状态提示
          this.$message({
            message: res.message,
            type: "success",
          });


          this.addUser.userId = '',
            this.addUser.userName = '',
            this.addUser.password = '',
            this.addDialogVisible = false
          this.selectUser();

        }).catch(() => { })
    }
  },

}

</script>